package org.lq.us.service.impl;

import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.lq.us.commons.Page;
import org.lq.us.dao.UsersDao;
import org.lq.us.dao.impl.UsersDaoImpl;
import org.lq.us.entity.Users;
import org.lq.us.query.UsersQuery;
import org.lq.us.service.RoleService;
import org.lq.us.service.UsersService;
import org.lq.us.util.ConfigHelper;

public class UsersServiceImpl implements UsersService {

	private UsersDao userDao = new UsersDaoImpl();
	private RoleService roleSerivce = new RoleServiceImpl();
	
	@Override
	public boolean save(Users u) {
		String oldPwd= u.getPassword();
		
		String newPwd = DigestUtils.md5Hex(oldPwd+u.getUserName());
		u.setPassword(newPwd);
		
		return userDao.save(u)>0;
	}

	@Override
	public boolean update(Users u) {
		
		if(StringUtils.isNoneBlank(u.getPassword())) {
			//如果用户填写密码,将填写的面加密
			String oldPwd= u.getPassword();
			String newPwd = DigestUtils.md5Hex(oldPwd+u.getUserName());
			u.setPassword(newPwd);
		}else {
			//用户没有设置密码
			String pwd= userDao.getPassword(u.getId());
			u.setPassword(pwd);
		}
		
		
		return userDao.update(u)>0;
	}

	@Override
	public boolean delete(int id) {
		return userDao.delete(id)>0;
	}

	@Override
	public Users getById(int id) {
		return userDao.getById(id);
	}

	@Override
	public void findPageQuery(Page<Users> page, UsersQuery uq) {
		userDao.findPageQuery(page, uq);
		List<Users> list = page.getList();
		for (Users users : list) {
			int rid= users.getRid();
			users.setRole(roleSerivce.getById(rid));
			users.setHead_icon(ConfigHelper.NewWordImgPath()+users.getHead_icon());
		}
		

	}

	@Override
	public int getCountQuery(UsersQuery uq) {
		return userDao.getCountQuery(uq);
	}

	@Override
	public boolean getByName(String name) {
		return userDao.getByName(name) > 0;
	}

	@Override
	public Users login(String userName, String pwd,boolean... bool) {
		if(bool.length>0) {
			if(bool[0]) {
				return userDao.login(userName, pwd);
			}
		}
		String newPwd = DigestUtils.md5Hex(pwd+userName);
		return userDao.login(userName,newPwd);
	}

}
